<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row :gutter="10">
        <el-col :span="6">
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              :class="['dbbottom',index1 === 0? 'dbtop':'','center']"
              v-for="(item1,index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeTag(scope.row,item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级三级权限 -->
              <el-col :span="19">
                <!-- 二级权限 -->
                <el-row
                  :class="[index2 === 0? '':'dbtop','center']"
                  v-for="(item2,index2) in item1.children"
                  :key="item2.id"
                >
                  <el-col :span="6">
                    <el-tag
                      type="success"
                      closable
                      @close="removeTag(scope.row,item2.id)"
                    >{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限 -->
                  <el-col :span="19">
                    <el-tag
                      type="warning"
                      v-for="(item3,index3) in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeTag(scope.row,item3.id)"
                    >{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="角色列表" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" width="300px">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editDialog(scope.row.id)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeUser(scope.row.id)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="assignPermissions(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色弹框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="40%" @close="addDialogClose">
      <el-form :model="addFrom" :rules="addFromRules" class="addFrom" ref="addFromRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addFrom.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addFrom.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户对话框 -->
    <el-dialog title="修改用户" :visible.sync="showEditDialog" width="40%" @close="editDialogClose">
      <!-- 内容 -->
      <span>
        <el-form :model="editUser" :rules="addFromRules" ref="editFormRef" label-width="100px">
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="editUser.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="editUser.roleDesc"></el-input>
          </el-form-item>
        </el-form>
      </span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="showPermissions" width="30%">
      <el-tree
        :data="perList"
        :props="treeProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defKeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showPermissions = false">取 消</el-button>
        <el-button type="primary" @click="subRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //所有角色列表数据
      rolesList: [],
      //添加角色弹框是否显示
      addDialogVisible: false,
      //修改角色弹框是否显示
      showEditDialog: false,
      //分配权限弹框是否显示
      showPermissions: false,
      //添加用户数据 绑定对象
      addFrom: {
        roleName: "",
        roleDesc: ""
      },
      addFromRules: {
        username: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" }
        ]
      },
      //保存通过id获取的参数
      editUser: {},
      //保存获取权限
      perList: [],
      //分配权限 树形控件 绑定对象
      treeProps: {
        label: "authName",
        childern: "children"
      },
      //默认选中的id 值
      defKeys: [],
      //保存当前即将分配权限的id
      roleId: ''
    };
  },
  created() {
    this.getRolesList();
  },
  methods: {
    //获取所有角色列表
    async getRolesList() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        return this.$message.error("获取数据失败！");
      }
      this.rolesList = res.data;
      console.log(res);
    },
    //点击按钮，添加角色事件
    addRoles() {
      this.$refs.addFromRef.validate(async valid => {
        if (!valid) return;
        //发送请求
        const { data: res } = await this.$http.post("roles", this.addFrom);
        if (res.meta.status == 201) {
          this.$message.success("添加角色成功！");
        } else {
          this.$message.error("添加角色失败！");
        }
        //添加后让 弹框消失
        this.addDialogVisible = false;
        //然后重新请求数据
        this.getRolesList();
      });
    },
    //监听添加角色 关闭事件
    addDialogClose() {
      this.$refs.addFromRef.resetFields();
    },
    //修改角色内容
    async editDialog(id) {
      const { data: res } = await this.$http.get("roles/" + id);
      if (res.meta.status !== 200) {
        return this.$message.error("请求失败！");
      }
      this.editUser = res.data;
      this.showEditDialog = true;
    },
    //监听修改对话框关闭重置
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //监听修改对话框提交操作
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "roles/" + this.editUser.roleId,
          {
            roleName: this.editUser.roleName,
            roleDesc: this.editUser.roleDesc
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("修改失败！");
        }
        this.showEditDialog = false;
        this.getRolesList();
        this.$message.success("修改成功！");
      });
    },
    //删除用户事件
    removeUser(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete("roles/" + id);
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败！");
          }
          this.getRolesList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //更具id 删除权限
    removeTag(role, id) {
      console.log(role.id, id);
      this.$confirm("此操作将永久删除该权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `roles/${role.id}/rights/${id}`
          );
          if (res.meta.status !== 200) {
            return this.$message.error("删除失败！");
          }
          role.children = res.data;
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //分配权限
    async assignPermissions(role) {
        this.roleId = role.id
      this.defKeys = []
      const { data: res } = await this.$http.get("rights/tree");
      if (res.meta.status !== 200) {
        return this.$message.error("获取权限失败！");
      }
      this.perList = res.data;
      //获取三级节点的id
      this.getdefKeys(role, this.defKeys);
      this.showPermissions = true;
    },
    //通过递归 获取三级权限 并保存
    getdefKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach(item => {
        this.getdefKeys(item, arr);
      });
    },
    //分配权限 提交
    async subRights() {
        const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        const idStr = keys.join(',')
        const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
    console.log(this.roleId)        
        if(res.meta.status !== 200) {
            return this.$message.error('分配权限失败！')
        }
        this.$message.success('分配权限成功!')
        this.getRolesList()
        this.showPermissions = false
    }
  }
};
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 20px;
}
.el-tag {
  margin: 7px;
}
.dbtop {
  border-top: 1px solid #eeeeee;
}
.dbbottom {
  border-bottom: 1px solid #eeeeee;
}
.center {
  display: flex;
  align-items: center;
}
</style>